package dtm

import (
	"context"
	"database/sql"
	"google.golang.org/grpc/codes"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/dtm-labs/client/dtmcli"
	"github.com/dtm-labs/client/dtmgrpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateIntegralTransactionLogRevertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateIntegralTransactionLogRevertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateIntegralTransactionLogRevertLogic {
	return &UpdateIntegralTransactionLogRevertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateIntegralTransactionLogRevertLogic) UpdateIntegralTransactionLogRevert(in *user.UpdateIntegralTransactionLogReq) (*user.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("UpdatePromotionLogRaw UpdatePromotionLogReq: %+v", in))
	// UserId:10001 OrderId:8 Logs:{ActivityId:2 ActivityRuleId:2 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:1 ActivityRuleId:1 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:0 ActivityRuleId:0 CouponTemplateId:1 CouponId:1}
	if len(in.Ids) == 0 {
		return nil, nil
	}

	var goodsId uint64
	if in.GoodsId != nil && *in.GoodsId > 0 {
		goodsId = *in.GoodsId
	}
	// 获取子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, resultx.StatusError(resultx.DTM_ERROR, err.Error())
	}

	// 开启子事务屏障
	err = barrier.CallWithDB(l.svcCtx.DB, func(tx *sql.Tx) error {
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				log, err := l.svcCtx.CurrentUser.FindOneNoCacheIntegralTransactionLog(l.ctx, tx, id)
				if err != nil {
					logx.Errorw("UpdateIntegralTransactionLogRaw FindOneNoCacheIntegralTransactionLog Insert err", logx.Field("detail", err.Error()))
					return resultx.StatusError(resultx.DB_ERROR, "")
				}

				log.Status = uint16(globalkey.StatusExpired)
				if log.ProductID == goodsId {
					log.Status = uint16(globalkey.StatusExpired)
				}
				log.UpdatedAt = now
				err = l.svcCtx.CurrentUser.UpdateIntegralTransactionLog(l.ctx, tx, log)
				if err != nil {
					logx.Errorw("UpdateIntegralTransactionLogRaw UpdateIntegralTransactionLog Insert err", logx.Field("detail", err.Error()))
					return resultx.StatusError(resultx.DB_ERROR, "")
				}
			}
		}

		return nil
	})

	// 不再重试，走回滚
	if err == dtmcli.ErrFailure {
		return nil, resultx.StatusError(uint32(codes.Aborted), dtmcli.ResultFailure)
	}

	if err != nil {
		return nil, err
	}

	return &user.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
